package org.tekmob.remindpal.controller;

import java.util.Calendar;
import java.util.List;

import org.tekmob.remindpal.R;
import org.tekmob.remindpal.model.Reminder;
import org.tekmob.remindpal.model.ReminderDAO;

import android.app.Activity;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;

/** 
 * This activity will be called when
 * Option menu "Send Reminder" clicked
 * 
 * When button "Send" clicked apps will send Reminder Configuration Message
 * @author Annisa
 * 
 */

public class SendReminder extends Activity {

	public static final int PICK_CONTACT    = 1;
	public TimePicker timePicker;
	public Calendar cal;
	public ReminderDAO dao;
	Calendar mcurrentTime;
	int hour;
	int minute;
	//Initiate Reminder Column
	int _id;
	String _name;
	int _date;
	int _month;
	int _year;
	int _hour;
	int _minute;
	String _sound;
	String _vibrate="false";
	String _increase="false";
	String _move="false";
	String _shake="false";
	EditText pal;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);	
		setContentView(R.layout.activity_send_reminder);

		cal = Calendar.getInstance();

		//Choose Pal
		pal = (EditText) findViewById(R.id.choose_pal);
		pal.setOnClickListener(new OnClickListener() {

			/*
			 * On click, show contact picker
			 * @see android.view.View.OnClickListener#onClick(android.view.View)
			 */
			@Override
			public void onClick(View v) {
				//TODO Auto-generated method stub
				Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
				pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
				startActivityForResult(pickContactIntent, PICK_CONTACT);

			}

		});

		//Setting Name
		final EditText name = (EditText) findViewById(R.id.name2);

		//Setting Time
		final EditText time = (EditText)findViewById(R.id.time2) ;
		time.setOnClickListener(new OnClickListener() {

			/*
			 * On click, show Time Picker
			 * @see android.view.View.OnClickListener#onClick(android.view.View)
			 */
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Calendar mcurrentTime = Calendar.getInstance();
				int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
				int minute = mcurrentTime.get(Calendar.MINUTE);
				TimePickerDialog mTimePicker = new TimePickerDialog(SendReminder.this, new TimePickerDialog.OnTimeSetListener() {
					@Override
					public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
						time.setText( "" + selectedHour + ":" + selectedMinute);
						cal.set(Calendar.HOUR_OF_DAY, selectedHour);
						cal.set(Calendar.MINUTE, selectedMinute);
						_hour = selectedHour;
						_minute = selectedMinute;
					}
				}, hour, minute, true);
				mTimePicker.setTitle("Select Time");
				mTimePicker.show();

			}
		});

		//Setting Date
		final Spinner date = (Spinner)findViewById(R.id.choose_date2);
		String[] itemsDate = {"", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
				"11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
				"21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" };
		ArrayAdapter<String> dateList = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, itemsDate);
		dateList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		date.setAdapter(dateList);


		//Setting Month
		final Spinner month = (Spinner)findViewById(R.id.choose_month2);
		String[] itemsMonth = {"", "January", "February", "March", "April", "May", "June", "July", "August", "September",
				"October", "November", "December"};
		ArrayAdapter<String> monthList = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, itemsMonth);
		monthList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		month.setAdapter(monthList);

		//Setting Year
		final Spinner year = (Spinner)findViewById(R.id.choose_year2);
		String[] itemsYear = { "", "2013", "2014", "2015"};
		ArrayAdapter<String> yearList = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, itemsYear);
		yearList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		year.setAdapter(yearList);


		//Check list Vibrate
		final CheckBox vibrate = (CheckBox) findViewById(R.id.vibrate2);
		vibrate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(vibrate.isChecked()) {
					_vibrate = "true";
				} else _vibrate = "false";
			}

		});

		//Check list increasing Sound
		final CheckBox increase = (CheckBox) findViewById(R.id.increasing_sound2);
		increase.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(increase.isChecked()) {
					_increase = "true";
				} else _increase = "false";
			}

		});


		//Check list Move
		final CheckBox move = (CheckBox) findViewById(R.id.check_move2);
		move.setOnCheckedChangeListener( new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				// TODO Auto-generated method stub
				if(move.isChecked()) {
					_move = "true";
				} else _move = "false";
			}

		});

		//Shake to Stop
		final CheckBox shake = (CheckBox) findViewById(R.id.check_shake2);
		shake.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(shake.isChecked()) {
					_shake = "true";
				} else _shake = "false";
			}

		});

		// Click button "Send Reminder"
		Button send = (Button) findViewById(R.id.send);
		send.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				dao = new ReminderDAO(SendReminder.this);
				
				_name = name.getText().toString();
				_date = Integer.parseInt(date.getSelectedItem().toString());
				if (month.getSelectedItem().toString()== "January") {
					_month = 0;
				} else if (month.getSelectedItem().toString()== "February") {
					_month = 1;
				} else if (month.getSelectedItem().toString()== "March") {
					_month = 2;
				} else if (month.getSelectedItem().toString()== "April") {
					_month = 3;
				} else if (month.getSelectedItem().toString()== "May") {
					_month = 4;
				} else if (month.getSelectedItem().toString()== "June") {
					_month = 5;
				} else if (month.getSelectedItem().toString()== "July") {
					_month = 6;
				} else if (month.getSelectedItem().toString()== "August") {
					_month = 7;
				} else if (month.getSelectedItem().toString()== "September") {
					_month = 8;
				} else if (month.getSelectedItem().toString()== "October") {
					_month = 9;
				} else if (month.getSelectedItem().toString()== "November") {
					_month = 10;
				} else if (month.getSelectedItem().toString()== "December") {
					_month = 11;
				} 
				_year = Integer.parseInt(year.getSelectedItem().toString());
				_id = 5 + (int)(Math.random() * ((2000 - 5) + 1));
				List<Reminder> checkID = dao.getReminder();
				for (int i = 0; i < checkID.size(); i++) {
					if (checkID.get(i).getId()== _id) {
						_id = 5 + (int)(Math.random() * ((2000 - 5) + 1));
					}
				}

				//Setting up for sending SMS
				String isiSms = "RemindPal " +_id+" "+_name+" "+_date+" "+_month+" "+_year+" "+_hour+" "+_minute+" "+"Default"+" "+_vibrate+" "+_increase+" "+_move+" "+_shake;
				//String isiSms = "RemindPal 11 nama 1 11 2003 1 55 sound vibrate increase move shake";
				String noHp = pal.getText().toString();
				sendSMS(noHp, isiSms);
				//When sending SMS finished, back to ShowReminder
				Intent newReminder = new Intent(getApplicationContext(),
						ShowReminder.class);
				startActivity(newReminder);

			}
		});
	}

	/*
	 * Method to send SMS
	 */
	private void sendSMS(String phoneNumber, String message) {
		String SENT = "SMS_SENT";
		String DELIVERED = "SMS_DELIVERED";

		PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
				SENT), 0);

		PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
				new Intent(DELIVERED), 0);

		registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					Toast.makeText(getBaseContext(), "Reminder sent",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
					Toast.makeText(getBaseContext(), "Generic failure, Reminder can not be sent",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_NO_SERVICE:
					Toast.makeText(getBaseContext(), "No service, Reminder can not be sent",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_NULL_PDU:
					Toast.makeText(getBaseContext(), "Null PDU",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					Toast.makeText(getBaseContext(), "Radio off",
							Toast.LENGTH_SHORT).show();
					break;
				}
			}

		}, new IntentFilter(SENT));

		registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					Toast.makeText(getBaseContext(), "Reminder delivered",
							Toast.LENGTH_SHORT).show();
					break;
				case Activity.RESULT_CANCELED:
					Toast.makeText(getBaseContext(), "Reminder not delivered",
							Toast.LENGTH_SHORT).show();
					break;
				}
			}
		}, new IntentFilter(DELIVERED));

		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
	}

	/*
	 * Setting up activity result for getting phone number
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	public void onActivityResult(int reqCode, int resultCode, Intent data) {
		super.onActivityResult(reqCode, resultCode, data);

		switch (reqCode) {
		case (PICK_CONTACT):
			if (resultCode == RESULT_OK) {
				Uri contactUri = data.getData();
				String[] projection = {Phone.NUMBER};

				Cursor cursor = getContentResolver()
						.query(contactUri, projection, null, null, null);
				cursor.moveToFirst();

				int column = cursor.getColumnIndex(Phone.NUMBER);
				String number = cursor.getString(column);
				pal.setText(number);
				// Do something with the phone number...
			}



		break;
		}
	}

	/*
	 * Initiate Option menu
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.list_reminder, menu);
		return true;

	}

	/*
	 * Option Menu Handler
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.new_reminder:
			// click on create item
			Intent newReminder = new Intent(getApplicationContext(),
					DetailReminder.class);
			startActivity(newReminder);
			break;
		case R.id.show:
			// click on show item
			Intent showReminder = new Intent(getApplicationContext(),
					ShowReminder.class);
			startActivity(showReminder);
			break;
		case R.id.send:
			// click on send item
			Intent sendReminder = new Intent(getApplicationContext(),
					SendReminder.class);
			startActivity(sendReminder);
			break;
		}
		return true;
	}
}
